<?php
namespace app\beautiful\controller\admin\appointment;
use app\BaseController;
use app\beautiful\model\appointment\AppointmentModel;
use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\appointment\TechnicianProjectModel;
use app\beautiful\model\appointment\TechnicianSchedulingModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\DataLogic;
use app\common\logic\SmsLogic;
use app\common\model\ShopStoreModel;

class Scheduling extends BaseController{
    public function show()
    {
        $day=$this->request->param('day');
        $store_id = $this->request->param('store_id/d',0);
        if(empty($day)) return $this->error('参数错误');
        if(false === strtotime($day.' 00:00:00')) return $this->error('参数错误');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0]
        ];
        
       
        $technician_model=new TechnicianModel();
        $technician_model = $technician_model->with(['schedulings'=>function($query) use ($day){
            $query->with(['project'])->where([['is_delete','=',0],['day','=',$day]]);
        }]);
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        $return = DataLogic::getDataList($technician_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        $total = $return['total'];
        if(!empty($return['list']) && $store_id > 0) {
            foreach($return['list'] as $key => $value) {
                if(empty($value['store'])) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
                $store = explode(',',$value['store']);
                if(!in_array($store_id,$store)) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
            }
            $return['list'] = array_values($return['list']);
            $return['total'] = $total;
        }
        
        $where_store = [
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['enable','=',1],
        ];
        $field='*';
        $order=['is_main'=>'asc','add_time'=>'desc'];
        $store = ShopStoreModel::where($where_store)->field($field)->order($order)->select()->toArray();
        $return['store'] = $store;
        $return['store_id'] = $store_id;
        return $this->success($return);
    }

    public function showTechnicianFromScheduling()
    {
        $technician_id=$this->request->param('technician_id/d',0);
        $day=$this->request->param('day');

        if($technician_id==0) return $this->error('技师不存在');
        if(empty($day)) return $this->error('参数错误');
        if(false === strtotime($day.' 00:00:00')) return $this->error('参数错误');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error('技师不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error('技师不存在');
        if($technician->is_delete != 0)  return $this->error('技师不存在');
        if($technician->status != 1) return $this->error('技师已经不在职了');

        $scheduling_time=TechnicianSchedulingModel::where([
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
            ['day','=',$day],
            ['is_delete','=',0]
        ])->field('start_time,end_time')->order(['start_time'=>'asc'])->select()->toArray();

        $info=[
            'face'=>$technician->face,
            'name'=>$technician->name,
            'mobile'=>$technician->mobile,
            'scheduling_time'=>$scheduling_time
        ];

        return $this->success(['info'=>$info]);
    }

    public function getProjectFromScheduling()
    {
        $technician_id = $this->request->param('technician_id/d',0);
        $store_id = $this->request->param('store_id/d',0);
        if($technician_id==0) return $this->error('技师不存在');
        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error('技师不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error('技师不存在');
        if($technician->is_delete != 0)  return $this->error('技师不存在');
        if($technician->status != 1) return $this->error('技师已经不在职了');
        // if($store_id==0) return $this->error('门店不存在');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];

        $bind_where=[
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$technician_id],
            ['is_delete','=',0],
        ];

        $project_ids=TechnicianProjectModel::where($bind_where)->column('project_id') ?? [];
        $where[]=['project_id','in',$project_ids];
        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        $return=DataLogic::getDataList($project_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        $total = $return['total'];
        if(!empty($return['list']) && $store_id > 0) {
            foreach($return['list'] as $key => $value) {
                if(empty($value['store'])) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
                $store = explode(',',$value['store']);
                if(!in_array($store_id,$store)) {
                    unset($return['list'][$key]);
                    $total = $total - 1;
                }
            }
            $return['list'] = array_values($return['list']);
            $return['total'] = $total;
        }
        return $this->success($return);

    }

    public function save()
    {
        $today=date("Y-m-d",$this->request->time());
        $technician_id=$this->request->param('technician_id/d',0);
        $day=$this->request->param('day');
        $scheduling_time=$this->request->param('scheduling_time/a',[]);
        $project_id=$this->request->param('project_id/d',0);
        $appointment_num=$this->request->param('appointment_num/d',0);

        if($technician_id==0) return $this->error('技师不存在');
        if($project_id==0) return $this->error('请选择服务项目');
        if(empty($day)) return $this->error('请选择预约日期');
        if(false === strtotime($day.' 00.00.00')) return $this->error('请选择预约日期');
        if($day<$today) return $this->error('预约日期不能低于今天');
        if(empty($scheduling_time) || !is_array($scheduling_time) ||count($scheduling_time)!=2) return $this->error('请选择预约时间');
        $start_time=$scheduling_time[0];$end_time=$scheduling_time[1];
        if(false === $start_time_unix=strtotime($day.' '.$start_time.':00')) return $this->error('请选择预约开始时间');
        if($start_time_unix<=$this->request->time()) return $this->error('预约开始时间低于当前时间');
        if(false === $end_time_unix=strtotime($day.' '.$end_time.':00')) return $this->error('请选择预约结束时间');
        $interval=$end_time_unix-$start_time_unix;
        if($interval<=0) return $this->error('预约开始时间不能大于结束时间');
        if($interval%1800!=0)return $this->error('预约时间间隔必须是30分钟的整倍');
        if(empty($appointment_num) || $appointment_num<=0) return $this->error('请输入同时段预约人数，且不能小于0');

        if(null === $technician = TechnicianModel::find($technician_id)) return $this->error('技师不存在');
        if($technician->shop_id != $this->request->shopId) return $this->error('技师不存在');
        if($technician->is_delete != 0)  return $this->error('技师不存在');
        if($technician->status != 1) return $this->error('技师已经不在职了');

        if(null === $project = ProjectModel::find($project_id)) return $this->error('项目不存在，请重新选择');
        if($project->shop_id != $this->request->shopId) return $this->error('项目不存在，请重新选择');
        if($project->is_delete != 0) return $this->error('项目不存在，请重新选择');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['technician_id','=',$technician_id],
            ['day','=',$day],
        ];


        if((null !== TechnicianSchedulingModel::where($where)->whereRaw("NOT ((end_time <= '{$start_time}') OR (start_time >= '{$end_time}'))")->find())){
            return $this->error('该时段与别的时间段重叠了,请重新选择');
        }

        $technician_scheduling_model= new TechnicianSchedulingModel();
        $technician_scheduling_model->shop_id=$this->request->shopId;
        $technician_scheduling_model->project_id=$project_id;
        $technician_scheduling_model->technician_id=$technician_id;
        $technician_scheduling_model->day=$day;
        $technician_scheduling_model->start_time=$start_time;
        $technician_scheduling_model->end_time=$end_time;
        $technician_scheduling_model->appointment_num=$appointment_num;
        $technician_scheduling_model->save();
        return $this->success('添加成功');

    }

    public function del()
    {
        $scheduling_id=$this->request->param('scheduling_id/d',0);
        if($scheduling_id==0) return $this->error('排班不存在');

        if(null === $technician_scheduling = TechnicianSchedulingModel::find($scheduling_id))  return $this->error('排班不存在');
        if($technician_scheduling->shop_id != $this->request->shopId)  return $this->error('排班不存在');
        if($technician_scheduling->is_delete != 0)  return $this->error('排班不存在');

        $technician_scheduling->is_delete=1;
        $technician_scheduling->save();

        $appointment=AppointmentModel::where([
            ['shop_id','=',$this->request->shopId],
            ['scheduling_id','=',$scheduling_id],
            ['status','in',[1,4]]
        ])->select()->toArray();
        if(!empty($appointment)){
            $mobiles=[];
            foreach ($appointment as $k => $v){
                $appointment[$k]['status']=-1;
                $appointment[$k]['cancel_time']=$this->request->time();
                $appointment[$k]['reason']='技师排班删除导致的取消';
                $appointment[$k]['operate_type']=2;
                $appointment[$k]['operate_id']=$this->request->accountId;
                $appointment[$k]['operate_name']=$this->request->account->name;
                $appointment[$k]['operate_mobile']=$this->request->account->mobile;
                $mobiles[]=$v['member_mobile'];
            }
            $appointment_model=new AppointmentModel();
            $appointment_model->saveAll($appointment);

            //发送短信给用户
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->cancel_appointment==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'xm'=>$appointment[0]['project_name'],
                        ];
                        $sms_logic->send($this->request->shopId,$mobiles,$params,'cancelAppointment');
                    }
                }
            }catch (\Exception $e){

            }
        }

        return $this->success('删除成功');
    }
}
